﻿namespace Cellfish.Toolbox.Facts.Slow.TaskSchedulers
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    using Cellfish.Test;
    using Cellfish.Toolbox.TaskSchedulers;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class PrivateThreadPoolTaskSchedulerFacts
    {
        private PrivateThreadPoolTaskScheduler scheduler = null;

        [TestCleanup]
        public void Cleanup()
        {
            if (this.scheduler != null)
            {
                this.scheduler.Shutdown(TimeSpan.FromSeconds(5));
                this.scheduler.Dispose();
            }
        }

        [TestMethod]
        public void Given_PrivateThreadPoolTaskScheduler_with_one_thread_When_executing_two_tasks_Then_second_task_does_not_execute_until_first_task_completes()
        {
            this.scheduler = new PrivateThreadPoolTaskScheduler(1);
            var factory = new TaskFactory(this.scheduler);
            var mre1 = new ManualResetEvent(false);
            var mre2 = new ManualResetEvent(false);
            var mre3 = new ManualResetEvent(false);
            var t1 = factory.StartNew(
                () =>
                    {
                        mre1.Set();
                        mre2.WaitOne();
                    });
            mre1.WaitOne();
            var t2 = factory.StartNew(
                () =>
                {
                    mre3.Set();
                });
            Assert.IsFalse(mre3.WaitOne(TimeSpan.FromSeconds(1)));
            mre2.Set();
            Assert.IsTrue(mre3.WaitOne(TimeSpan.FromSeconds(5)));
        }
    }
}
